<template>
  <div class="personal-page">
    <div class="main">
      <div class="personal-info">
        <div class="mt-title">用户资料</div>
        <div class="cont">
          <el-form
            class="info-box"
            label-width="96px"
            ref="accountInfoRef"
            :model="accountInfo"
            :rules="accountInfoRules">
            <div class="info-item">
              <el-form-item
                label="姓名"
                prop="userName">
                <el-input
                  v-model.trim="accountInfo.userName"
                  placeholder="请输入姓名"></el-input>
              </el-form-item>
              <el-form-item
                label="手机号"
                prop="mobile">
                <el-input
                  v-model.trim="accountInfo.mobile"
                  :disabled="true"
                  placeholder="请输入手机号"
                  oninput="this.value=this.value.replace(/\D/g,'')"
                  maxlength="11"></el-input>
              </el-form-item>
              <!-- <el-form-item label="性别">
                <el-radio-group v-model="accountInfo.gender">
                  <el-radio :label="0">男</el-radio>
                  <el-radio :label="1">女</el-radio>
                </el-radio-group>
              </el-form-item> -->
            </div>
            <div class="info-item">
              <el-form-item
                label="邮箱"
                prop="email">
                <el-input
                  v-model.trim="accountInfo.email"
                  placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <!-- <el-form-item
                label="扫码登录"
                prop="codeState">
                <p class="bind-btn"
                  v-if="!accountInfo.codeState"
                  @click="showScancode()">未绑定</p>
                <p class="bind-btn cancel"
                  v-else
                  @click="isShowUnbindScancode = true">解除绑定</p>
              </el-form-item> -->
            </div>
          </el-form>
          <div class="btn-box">
            <p class="btn save"
              @click="saveAccountInfo()">保存配置</p>
            <p class="btn edit"
              @click="showPasswordDialog()">修改密码</p>
          </div>
        </div>
      </div>
      <div class="auth-record">
        <div class="mt-title">已开通的权限</div>
        <div class="cont">
          <el-table
            class='table-border'
            :data="authRecordList"
            tooltip-effect='light'>
            <el-table-column
              type="index"
              label="序号"
              width="160px">
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="type"
              min-width='80px'
              label="类型">
              <template slot-scope="scope">
                {{scope.row.type | handleAccountType}}
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="modeName"
              min-width='110px'
              label="账号名称">
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="primit"
              min-width='110px'
              label="权限范围">
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="roleName"
              min-width='110px'
              label="角色">
            </el-table-column>
            <!-- <el-table-column
              show-overflow-tooltip
              prop="createTime"
              min-width='110'
              label="操作时间">
              <template slot-scope="scope">
                {{scope.row.createTime.slice(0, 10)}}
              </template>
            </el-table-column> -->
          </el-table>
          <el-pagination
            style="text-align:right;margin-top:18px!important;"
            background
            :page-size="pageSize"
            :page-sizes="pageSizesG"
            @size-change="handleSizeChange"
            :current-page="page"
            @current-change="handleCurrentChange"
            layout="sizes, prev, pager, next"
            :total="count">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 修改密码 -->
    <el-dialog
      width="600px"
      title="修改密码"
      :close-on-click-modal="false"
      :visible.sync="isShowPassword">
      <el-form
        class="password-info"
        :model="passwordInfo"
        :rules="passwordRules"
        ref="passwordInfoRef"
        label-width="104px"
        label-position="right">
        <el-form-item
          label="旧密码"
          prop="oldPass">
          <el-input
            placeholder="请输入旧密码"
            v-model.trim="passwordInfo.oldPass"
            show-password
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item
          label="新密码"
          prop="newPass">
          <el-input
            placeholder="请输入新密码"
            v-model.trim="passwordInfo.newPass"
            show-password
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="newPassRepeat">
          <el-input
            placeholder="请重复密码"
            v-model.trim="passwordInfo.newPassRepeat"
            show-password
            clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closePasswordDialog()">取消</el-button>
        <el-button size="small" type="primary" @click="confirmPassword()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 扫码绑定 -->
    <el-dialog
      custom-class="scancode-dialog"
      width="600px"
      title="微信绑定"
      :close-on-click-modal="false"
      :visible.sync="isShowScancode"
      @close="closeScancode()">
      <div
        class="scancode-cont"
        style="padding-bottom: 40px;"
        v-show="scanCodeStatus === 1">
        <p class="qrcode">
          <img src="https://test.saas.yuemia.com/mmbiz_jpg/wSAQiaXEKSBsYiadrdqIIJUUOJDvlSV5bFUvNLU4dmU3aeRLia3h4kE6EvZHxuCTYGEkhNxDjmkJZTlLohAIeslow/0" alt="">
        </p>
        <p class="descript">微信扫码绑定账号后，可使用扫码方式登录平台</p>
      </div>
      <div
        class="scancode-cont"
        v-show="scanCodeStatus === 2">
        <div class="qrcode invalid">
          <img src="https://test.saas.yuemia.com/mmbiz_jpg/wSAQiaXEKSBsYiadrdqIIJUUOJDvlSV5bFUvNLU4dmU3aeRLia3h4kE6EvZHxuCTYGEkhNxDjmkJZTlLohAIeslow/0" alt="">
          <p class="succ">扫码成功</p>
        </div>
        <p class="descript">请在手机微信上点击确认，完成绑定</p>
      </div>
      <div
        class="scancode-cont"
        style="padding-bottom: 40px;"
        v-show="scanCodeStatus === 3">
        <div class="qrcode invalid">
          <img :src="qrCodeUrl" alt="">
          <p class="succ">扫码成功</p>
        </div>
        <p class="descript">绑定成功，退出后重新登录即可使用扫码登录</p>
      </div>
      <div slot="footer"
        class="dialog-footer"
        v-show="scanCodeStatus === 2">
        <el-button
          size="small"
          type="primary"
          @click="resetScancode()">重新扫码</el-button>
      </div>
    </el-dialog>
    <!-- 解除扫码绑定 -->
    <el-dialog
      width="600px"
      title="解除绑定"
      :close-on-click-modal="false"
      :visible.sync="isShowUnbindScancode">
      <div class="unbind-scancode">
        <p class="descript">解除绑定之后将退出系统，进行重新登录和绑定。</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="isShowUnbindScancode = false">取消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="cancelBind()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    var validateEmail = (rule, value, callback) => {
      /* eslint-disable no-useless-escape */
      let res = /\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+/
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!res.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    var validatePass1 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码最低6个字符'))
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordInfo.newPass) {
        callback(new Error('两次输入密码不一致!'))
      } else if (value.length < 6) {
        callback(new Error('密码最低6个字符'))
      } else {
        callback()
      }
    }
    return {
      // 用户信息相关
      empId: '',
      accountInfo: {
        userName: '',
        mobile: '',
        gender: 0,
        email: '',
        codeState: false
      },
      accountInfoRules: {
        userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        email: [{required: true, validator: validateEmail, trigger: 'blur'}]
      },
      // 权限记录列表
      page: 1,
      pageSize: 10,
      count: 0,
      authRecordList: [],
      // 修改密码相关
      isShowPassword: false,
      passwordInfo: {
        oldPass: null,
        newPass: null,
        newPassRepeat: null
      },
      passwordRules: {
        oldPass: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPass: [
          { required: true, validator: validatePass1, trigger: 'blur' }
        ],
        newPassRepeat: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      // 扫码绑定
      isShowScancode: false,
      scanCodeStatus: 1, // 扫码状态:1代表未扫码,2代表扫码了未确认,3代表扫码了已确认(成功,失败的情况未考虑)
      qrCodeUrl: 'https://test.saas.yuemia.com/mmbiz_jpg/wSAQiaXEKSBsYiadrdqIIJUUOJDvlSV5bFUvNLU4dmU3aeRLia3h4kE6EvZHxuCTYGEkhNxDjmkJZTlLohAIeslow/0',
      timer: null,
      // 解除扫码绑定
      isShowUnbindScancode: false
    }
  },
  methods: {
    // 保存当前账号信息
    saveAccountInfo () {
      this.$refs.accountInfoRef.validate((valid) => {
        if (this.accountInfo.userName.length > 12) {
          return this.showWarnMsg('姓名最大长度为12字')
        }
        if (!this.checkTel(this.accountInfo.mobile)) {
          return this.showWarnMsg('请输入正确的手机号')
        }
        if (valid) {
          let params = {
            name: this.accountInfo.userName,
            account: this.accountInfo.mobile,
            // gender: this.accountInfo.gender,
            email: this.accountInfo.email
          }
          let url = `/user/account/${this.accountInfo.accountId}`
          this.posts(url, params).then(rsp => {
            if (rsp.data.code === 200) {
              this.showSucc('用户资料修改成功')
            } else if (rsp.data.code === 400) {
              this.showErrMsg('当前密码输入错误')
            }
          }).catch(e => {
            this.handleError(e)
          })
        }
      })
    },
    // 显示修改密码的蒙层
    showPasswordDialog () {
      this.isShowPassword = true
    },
    // 保存密码
    confirmPassword () {
      this.$refs.passwordInfoRef.validate((valid) => {
        if (valid) {
          let url = `${this.SERVICE_SYS}/account/update/password`
          let params = {
            mobile: this.accountInfo.mobile,
            oldPassword: this.passwordInfo.oldPass,
            newPassword: this.passwordInfo.newPass,
            refPassword: this.passwordInfo.newPassRepeat
          }
          this.post(url, params).then(rsp => {
            if (rsp.data.code === 200) {
              this.showSucc('用户密码修改成功')
              this.closePasswordDialog()
            } else if (rsp.data.code === 400) {
              this.showErrMsg('当前密码输入错误')
            }
          }).catch(e => {
            this.handleError(e)
          })
        }
      })
    },
    // 关闭修改密码的弹框
    closePasswordDialog () {
      this.isShowPassword = false
      this.passwordInfo = {
        oldPass: null,
        newPass: null,
        newPassRepeat: null
      }
    },
    // 设置扫码登录
    showScancode () {
      this.isShowScancode = true
      this.fetchQrcodeInfo()
      // 监听扫码状态
      // this.timer = setInterval(() => {
      //   this.fetchScanCodeStatus()
      // }, 1000)
    },
    // 重新扫码
    resetScancode () {
      this.fetchQrcodeInfo()
      this.scanCodeStatus = 1
    },
    // 获取二维码（用于绑定微信，实现扫码登录）
    fetchQrcodeInfo () {

    },
    // 获取扫码状态
    fetchScanCodeStatus () {
      let url = ``
      this.get(url).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          if (data) {
            switch (data.status) {
              case 0:
                this.scanCodeStatus = 1
                break
              case 1: // 扫码了未确认
                this.scanCodeStatus = 2
                break
              case 3: // 扫码了并确认了
                this.scanCodeStatus = 3
                clearInterval(this.timer)
                break
              default:
                break
            }
          }
        }
      })
    },
    // 关闭扫码弹框
    closeScancode () {
      clearInterval(this.timer)
      this.qrCodeUrl = ''
    },
    // 解除绑定
    cancelBind () {
      let url = ``
      this.posts(url).then(res => {
        if (res.data.code === 200) {
          this.showSucc(res.data.message)
          // 这里需要重新获取绑定状态
          this.isShowUnbindScancode = false
        }
      })
    },
    // 获取系统当前账号信息
    getAccountInfo () {
      let url = `${this.SERVICE_SYS}/account/current`
      this.get(url).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          if (data) {
            this.empId = data.empId
            this.accountInfo = {
              accountId: data.userId,
              userName: data.userName,
              mobile: data.account,
              gender: data.gender,
              email: data.email
            }
            sessionStorage.setItem('isAdmin', data.isAdmin)
            this.fetchAuthRecord()
          }
        }
      })
    },
    // 获取权限记录
    fetchAuthRecord () {
      let url = `/user/account/permit/${this.accountInfo.accountId}`
      let params = {
        currentPage: this.page,
        pageSize: this.pageSize
      }
      this.get(url, params).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          if (data) {
            this.count = +data.total
            if (data.list && data.list.length) {
              this.authRecordList = data.list
            } else {
              this.authRecordList = []
            }
          } else {
            this.authRecordList = []
          }
        }
      }).catch(err => {
        this.handleError(err)
      })
    },
    handleSizeChange (val) {
      this.page = 1
      this.pageSize = val
      this.fetchAuthRecord()
    },
    handleCurrentChange (val) {
      this.page = val
      this.fetchAuthRecord()
    }
  },
  filters: {
    handleAccountType (type) {
      switch (Number(type)) {
        case 1:
          return '订阅号'
        case 2:
          return '服务号'
        case 3:
          return '企业号'
        default:
          break
      }
    }
  },
  created () {
    this.getAccountInfo()
  }
}
</script>
<style lang="stylus" scoped>
.personal-page
  min-height 100%
  .main
    height 100%
    .mt-title
      width 100%
      height 51px
      line-height 50px
      padded_box(border-box, 0 30px)
      border-bottom 1px solid #EAEDF7
      font-size 14px
      color #22242F
    .cont
      width 100%
      padded_box(border-box, 30px 30px 34px)
    .personal-info,.auth-record
      width 100%
      background #fff
      border-radius 10px
      border: 1px solid #EAEDF7
      box-sizing border-box
    .personal-info
      .info-box
        width 100%
        display flex
        >>> .el-form-item__label
          padding 0 20px 0 0
        .info-item
          width 456px
          & + .info-item
            margin-left 50px
        .bind-btn
          display inline-block
          height 30px
          background #fff
          line-height 14px
          text-align center
          padded_box(border-box, 7px 20px)
          border-radius: 4px;
          border: 1px solid #4C84FF
          font-size 14px
          color #4C84FF
          cursor pointer
          &.cancel
            border: 1px solid #DCDFE6;
            color: rgba(96,98,102, 0.5);
      .btn-box
        display flex
        padded_box(border-box, 0 0 0 96px)
        .btn
          height 32px
          line-height 14px
          text-align center
          border-radius: 4px;
          padded_box(border-box, 8px 20px)
          border 1px solid #4C84FF
          font-size 14px
          &.save
            background #4C84FF
            color #fff
          &.edit
            background #fff
            color #4C84FF
            margin-left 12px
    .auth-record
      margin-top 8px
      height calc(100% - 322px)
      .cont
        padded_box(border-box, 30px 30px 20px)
      // >>> .el-table th
      //   &:first-child
      //     padding-left 20px
      // >>> .el-table td
      //   padding 16px 0
      //   &:first-child
      //     padding-left 20px
      >>> .el-table
        th
          font-size 12px
          &:first-child
            padding-left 20px
        td
          padding 16px 0
          font-size 12px
          .cell
            color #5E5E66 !important
          &:first-child
            padding-left 20px
// 修改密码的弹框
.password-info
  >>> .el-form-item__label
    padded_box(border-box, 0 20px 0 0)
// 绑定微信
.scancode-cont
  .qrcode
    width 130px
    height 130px
    margin 0 auto
    // border 1px solid #ddd
    // border-radius 4px
    position relative
    &.invalid
      img
        opacity 0.2
    img
      display block
      width 100%
      border-radius 4px
    .succ
      width 106px
      height: 40px;
      line-height 16px
      background: #FFFFFF url('~assets/img/icon_succ@2x.png') no-repeat 10px center / 16px;
      box-shadow: 0px 0px 6px 2px rgba(0, 0, 0, 0.06);
      border-radius: 8px;
      padded_box(border-box, 12px 10px 12px 38px)
      font-size 14px
      color #222222
      position absolute
      top 50%
      left 50%
      transform translate(-50%, -50%)
  .descript
    height 20px
    line-height 20px
    text-align center
    font-size: 14px;
    color: #7F7F7F
    margin 40px 0 0
// 解绑
.unbind-scancode
  padded_box(border-box, 30px 20px)
  .descript
    height 20px
    line-height 20px
    text-align center
    font-size: 14px;
    color: #22242F
</style>
